package org.havenapp.main;

import android.content.res.AssetFileDescriptor;
import android.graphics.SurfaceTexture;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Surface;

import java.util.Map;

/**
 * <p>统一管理MediaPlayer的地方,只有一个mediaPlayer实例，那么不会有多个视频同时播放，也节省资源。</p>
 * <p>Unified management MediaPlayer place, there is only one MediaPlayer instance, then there will be no more video broadcast at the same time, also save resources.</p>
 * Created by Nathen
 * On 2015/11/30 15:39
 */
public class JCMediaManager implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener {
    public static final int HANDLER_PREPARE = 0;
    public static final int HANDLER_RELEASE = 2;
    public static String TAG = "JCMediaManager4Video";
    public static JCMediaManager JCMediaManager;
    public static String CURRENT_PLAYING_URL;
    public static boolean CURRENT_PLING_LOOP;
    public static Map<String, String> MAP_HEADER_DATA;
    /**
     * 增加属性 start for buxiaoqing
     **/
    public MediaPlayer mediaPlayer = new MediaPlayer();
    HandlerThread mMediaHandlerThread;
    MediaHandler mMediaHandler;
    Handler mainThreadHandler;

    public JCMediaManager() {
        mMediaHandlerThread = new HandlerThread(TAG);
        mMediaHandlerThread.start();
        mMediaHandler = new MediaHandler((mMediaHandlerThread.getLooper()));
        mainThreadHandler = new Handler();
    }

    public static JCMediaManager instance() {
        if (JCMediaManager == null) {
            JCMediaManager = new JCMediaManager();
        }
        return JCMediaManager;
    }


    public static void play() {

        try {
            if (JCMediaManager.instance().mediaPlayer != null) {
                JCMediaManager.instance().onPrepared(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "play: Exception  prepare");
        }
    }


    public void prepare() {
        releaseMediaPlayer();
        Message msg = new Message();
        msg.what = HANDLER_PREPARE;
        mMediaHandler.sendMessage(msg);
    }


    public void releaseMediaPlayer() {
        outSideRelease();
    }

    public void outSideRelease() {
        Message msg = new Message();
        msg.what = HANDLER_RELEASE;
        mMediaHandler.sendMessage(msg);
    }


    @Override
    public void onPrepared(MediaPlayer mp) {
        Log.d(TAG, "onPrepared: Thread id = " + android.os.Process.myTid() + "  name = " + Thread.currentThread().getName());
        mediaPlayer.start();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        Log.d(TAG, "onCompletion: Thread id = " + android.os.Process.myTid() + "  name = " + Thread.currentThread().getName());

    }


    @Override
    public boolean onError(MediaPlayer mp, final int what, final int extra) {
        Log.d(TAG, "onError: Thread id = " + android.os.Process.myTid() + "  name = " + Thread.currentThread().getName());
        Log.d(TAG, "onError what - " + what + " extra - " + extra);

        return false;
    }

    @Override
    public boolean onInfo(MediaPlayer mp, final int what, final int extra) {
        Log.d(TAG, "onInfo: Thread id = " + android.os.Process.myTid() + "  name = " + Thread.currentThread().getName());
        Log.d(TAG, "onInfo what - " + what + " extra - " + extra);


        return false;
    }

    public class MediaHandler extends Handler {
        public MediaHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HANDLER_PREPARE:
                    try {
                        mediaPlayer.release();
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        AssetFileDescriptor fileDescriptor = HavenApp.mContext.getAssets().openFd("alarm.wav");
                        mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
                                fileDescriptor.getStartOffset(),
                                fileDescriptor.getLength());
                       /* if (CURRENT_PLAYING_URL.startsWith("file")) {
                            //播放本地缓存文件的方法
                            FileInputStream fis = new FileInputStream(new File(URI.create(CURRENT_PLAYING_URL)));
                            mediaPlayer.setDataSource(fis.getFD());
                        } else {
                            Class<MediaPlayer> clazz = MediaPlayer.class;
                            Method method = clazz.getDeclaredMethod("setDataSource", String.class, Map.class);
                            method.invoke(mediaPlayer, CURRENT_PLAYING_URL, MAP_HEADER_DATA);
                        }*/
                        mediaPlayer.setLooping(CURRENT_PLING_LOOP);
                        mediaPlayer.setOnPreparedListener(JCMediaManager.this);
                        mediaPlayer.setOnCompletionListener(JCMediaManager.this);
                        mediaPlayer.setScreenOnWhilePlaying(true);
                        mediaPlayer.setOnErrorListener(JCMediaManager.this);
                        mediaPlayer.setOnInfoListener(JCMediaManager.this);
                        mediaPlayer.prepareAsync();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case HANDLER_RELEASE:
                    mediaPlayer.release();
                    break;
                default:
                    break;
            }
        }
    }
}
